package com.itheima.tlias.aop;

import com.itheima.tlias.mapper.OperateLogMapper;
import com.itheima.tlias.pojo.OperateLog;
import com.itheima.tlias.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Slf4j
@Component
public class OperateLogAspect {
	@Autowired
	private OperateLogMapper operateLogMapper;

	@Pointcut("execution(* com.itheima.tlias.controller.*.save*(..)) || " +
			"execution(* com.itheima.tlias.controller.*.update*(..)) || " +
			"execution(* com.itheima.tlias.controller.*.delete*(..))")
	public void operateMethod() {
	}

	@Around("operateMethod()")
	public Object recordOperate(ProceedingJoinPoint pjp) throws Throwable {

		String ClssName = pjp.getTarget().getClass().getName();
		log.info("目标方法类型:{}", ClssName);
		String methodName = pjp.getSignature().getName();
		log.info("目标方法名称:{}", methodName);
		String methodParams = Arrays.toString(pjp.getArgs());
		log.info("目标方法参数:{}", methodParams);

		Long startTime = System.currentTimeMillis();
		Object result = pjp.proceed();
		Long endTime = System.currentTimeMillis();

		//Integer currentId = CurrentHolder.getCurrentId();

		OperateLog operateLog = new OperateLog();
		operateLog.setOperateEmpId(CurrentHolder.getCurrentId());
		operateLog.setOperateTime(LocalDateTime.now());
		operateLog.setClassName(ClssName);
		operateLog.setMethodName(methodName);
		operateLog.setMethodParams(methodParams);
		operateLog.setReturnValue(result.toString());
		operateLog.setCostTime(endTime - startTime);
		operateLogMapper.insert(operateLog);
		log.info("操作日志:{}", operateLog);
		return result;
	}
}
